package com.woniu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.user.exception.WebException;
import com.woniu.user.exception.WebExceptionCode;
import com.woniu.user.model.Account;
import com.woniu.user.model.Charge;
import com.woniu.user.dao.ChargeDao;
import com.woniu.user.service.AccountService;
import com.woniu.user.service.ChargeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-02-22
 */
@Service
public class ChargeServiceImpl extends ServiceImpl<ChargeDao, Charge> implements ChargeService {

    @Resource
    private AccountService accountService;


    // 支付成功的处理
    @Override
    public void paySuccess(String out_trade_no, String amount) {
        // 1.根据订单号获取 订单并确认状态
        Charge charge = this.getOne(new QueryWrapper<Charge>().eq("no", out_trade_no));
        if (charge == null)
            throw new WebException(WebExceptionCode.CHARGE_IS_NOT_EXISTS);
        if(!charge.getState().equals("支付中"))
            throw new WebException(WebExceptionCode.CHARGE_STATES_IS_NOT_CORRECT);

        // 2.修改订单状态
        charge.setState("已完成");
        charge.setTime(LocalDateTime.now());
        this.updateById(charge);

        // 3.修改数据库中的余额
        Integer userId = charge.getUserId();
        Account account = accountService.getById(userId);
        double money = Double.parseDouble(amount);
        BigDecimal cash = BigDecimal.valueOf(money);
        account.setBalance(account.getBalance().add(cash));
        accountService.updateById(account);
    }
}
